<?php

/**
 * 权限管理
 * @author gaofang
 * @date 2018-3-05 08:53
 */

namespace app\admin\controller;

use app\common\controller\Admin;
use app\admin\model\AdminMenu;
use app\admin\model\Admin as AdminMember;
use app\admin\model\AdminRole;
use think\Request;

class Power extends Admin {

    public $menuModel;
    public $memberModel;
    public $roleModel;

    public function __construct(\think\Request $request = null) {
        parent::__construct($request);
        $this->menuModel = new AdminMenu();
        $this->memberModel = new AdminMember();
        $this->roleModel = new AdminRole();
        $this->assign('adminStatus', config('admin_status'));
    }

    /**
     * 菜单管理[菜单列表]
     */
    public function menu() {
        $menuList = AdminMenu::where('is_del', 0)->field('id,parentid,name,m,c,a,list_order,level,display,data,is_del,false as open')->order('list_order')->select();
        $this->assign('menu', json_encode($menuList));
        return $this->fetch();
    }

    /**
     * 管理员列表
     */
    public function member() {
        $role = $this->roleModel->getCache();
        $list = $this->memberModel->order('roleid')->select();

        $this->assign('list', $list);
        $this->assign('role', array_column($role, 'rolename', 'id'));
        return $this->fetch();
    }

    /**
     * 角色[列表]
     * @return type
     */
    public function role() {
        $list = $this->roleModel->order('list_order')->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 编辑角色[ajax]
     * @return type
     */
    public function editRole() {
        $data = $this->request->only(['id', 'rolename', 'description', 'list_order', 'is_use']);
        if ($data['id']) {
            $result = $this->roleModel->update($data);
        } else {
            $result = $this->roleModel->create($data);
        }
        if ($result) {
            return $this->success('成功');
        } else {
            return $this->error('失败');
        }
    }

    /**
     * 编辑角色权限
     * @return type
     */
    public function editRolePriv($id) {

        //查询角色原有权限
        $rolePriv = db('admin_role_priv')->where('roleid', $id)->find();
        if ($this->request->isAjax()) {
            $param = $this->request->only(['id', 'priv']);
            $priv = isset($param['priv']) ? implode(',', $param['priv']) : '';
            if (!$rolePriv && !$priv) {
                $this->error('没有选择任何权限');
            }
            if ($rolePriv) {
                db('admin_role_priv')->where('id', $rolePriv['id'])->setField('privs', $priv);
            } else {
                db('admin_role_priv')->insert(['roleid' => $id, 'privs' => $priv]);
            }
            $this->success('成功');
        }
        $menuList = AdminMenu::where('is_del', 0)->field('id,parentid as pId,name,list_order,true as open,false as checked')->order('list_order')->select()->toArray();
        //查询角色原有权限
        if ($rolePriv) {
            $privArr = explode(',', $rolePriv['privs']);
            foreach ($menuList as &$menu) {
                if (in_array($menu['id'], $privArr)) {
                    $menu['checked'] = true;
                }
            }
        }

        $this->assign('menu', json_encode($menuList));
        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * 添加管理员
     */
    public function addMember() {
        $role = $this->roleModel->getCache();
        $this->assign('role', array_column($role, 'rolename', 'id'));
        if ($this->request->isPost()) {
            $data = $this->request->only(['username', 'password', 'nickname', 'email', 'roleid', 'is_use']);
            $member = new AdminMember();

            //校验邮件是否唯一
            if (!$member->checkEmailUnique($data['email'])) {
                $this->error('邮箱已存在');
            }

            $member->username = $data['username'];
            $member->nickname = isset($data['nickname']) ? $data['nickname'] : $data['username'];
            $member->email = $data['email'];
            $member->roleid = $data['roleid'];
            //$member->status = $data['is_use'];
            $member->created_at = time();
            $member->salt = create_randomstr();
            $member->password = md5($data['password'] . $member->salt);
            $member->save();

            //初始化权限
            /**
              if ($data['roleid']) {
              $rolePriv = db('admin_role_priv')->where('roleid', $data['roleid'])->find();
              $memberPrivData = [
              'memberid' => $member->id,
              'privs' => $rolePriv['privs']
              ];
              db('admin_member_priv')->insert($memberPrivData);
              } */
            $this->success('添加成功', 'power/member');
        }
        return $this->fetch();
    }

    /**
     * 重置用户权限
     * @param type $memberid
     * @param type $roleid
     */
    public function resetMemberPriv($memberid, $roleid) {
        $memberPriv = db('admin_member_priv')->where('memberid', $memberid)->find();
        $rolePriv = db('admin_role_priv')->where('roleid', $roleid)->find();
        $memberPrivData = [
            'memberid' => $memberid,
            'privs' => $rolePriv['privs']
        ];
        if ($memberPriv) {
            db('admin_member_priv')->where('memberid', $memberid)->update(['privs' => $rolePriv['privs']]);
        } else {
            db('admin_member_priv')->insert($memberPrivData);
        }
        $this->success('初始化成功');
    }

    /**
     * 编辑管理员
     * @return int
     */
    public function editMember($id = 0) {
        $uid = (int) $id;
        if (!$uid) {
            $this->redirect('power/member');
        }
        $member = $this->memberModel->find($uid);
        $role = $this->roleModel->getCache();
        $this->assign('role', array_column($role, 'rolename', 'id'));

        if ($this->request->isPost()) {
            $data = $this->request->only(['username', 'password', 'nickname', 'email', 'roleid', 'status']);

            //校验邮件是否唯一
            if (!$member->checkEmailUnique($data['email'], $uid)) {
                $this->error('邮箱已存在');
            }

            $member->username = $data['username'];
            //$member->nickname = $data['nickname'];
            $member->email = $data['email'];
            $member->roleid = $data['roleid'];
            $member->status = $data['status'];
            if ($data['password']) {
                $member->password = md5($data['password'] . $member->salt);
            }
            $member->save();
            $this->success('更新成功', 'power/member');
        }
        $this->assign('info', $member);
        return $this->fetch();
    }

    /**
     * 编辑管理员权限
     * @param type $id
     * @return type
     */
    public function editMemberPriv($id) {
        //查询角色原有权限
        $memberPriv = db('admin_member_priv')->where('memberid', $id)->find();
        if ($this->request->isAjax()) {
            $param = $this->request->only(['id', 'priv']);
            $priv = isset($param['priv']) ? implode(',', $param['priv']) : '';
            if (!$memberPriv && !$priv) {
                $this->error('没有选择任何权限');
            }
            if ($memberPriv) {
                db('admin_member_priv')->where('id', $memberPriv['id'])->setField('privs', $priv);
            } else {
                db('admin_member_priv')->insert(['memberid' => $id, 'privs' => $priv]);
            }
            $this->success('成功');
        }
        $menuList = AdminMenu::where('is_del', 0)->field('id,parentid as pId,name,list_order,true as open,false as checked')->order('list_order')->select()->toArray();
        //查询角色原有权限
        if ($memberPriv) {
            $privArr = explode(',', $memberPriv['privs']);
            foreach ($menuList as &$menu) {
                if (in_array($menu['id'], $privArr)) {
                    $menu['checked'] = true;
                }
            }
        }
        $this->assign('menu', json_encode($menuList));
        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * 编辑菜单
     */
    public function editMenu() {
        $data = $this->request->param();
        $data['a'] = $data['aa'];
        unset($data['aa']);
        if ($data['id']) {
            $result = $this->menuModel->update($data);
        } else {
            $result = $this->menuModel->create($data);
        }
        $menuList = AdminMenu::where('is_del', 0)->field('id,parentid,name,m,c,a,list_order,level,display,data,is_del,false as open')->order('list_order')->select();
        
        if ($result) {
            return $this->success('成功','',$menuList);
        } else {
            return $this->error('失败');
        }
    }

    /**
     * 删除菜单
     * @return type
     */
    public function delMenu() {
        $data = $this->request->param();
        $result = $this->menuModel->where($data)->delete();
        $menuList = AdminMenu::where('is_del', 0)->field('id,parentid,name,m,c,a,list_order,level,display,data,is_del,false as open')->order('list_order')->select();
        return $this->success($result,'',$menuList);
    }
    
    /**
     * 设置菜单排序
     * @param \app\admin\controller\Request $request
     * @return type
     */
    public function setMenuSort(Request $request) {
        $data = $request->param();

        foreach ($data as $key => $typeid) {
            $this->menuModel->where('id', $typeid)->update(['list_order' => $key]);
        }

        return $this->success('success', '', $data);
    }

    /**
     * 生成菜单缓存文件
     */
    public function setMenuCache() {
        $this->menuModel->setLeftMenuCache();
    }

}
